require.config({
    paths: {
        'jquery': 'http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js',
        'vue': '../encaptool/encvue',
        'iview': '../utiltool/iview/iview',
        'bmap': 'http://api.map.baidu.com/api?v=2.0&ak=9whTPxXrl8zvW3gjiAaoPa59gFekKK9I',
        'async': '../utiltool/requirejsplugins/src/async',
        'axios': '../encaptool/encaxios',
        'heatmap': '../utiltool/heatmap/Heatmap_min'
    },
    shim: {
        'iview': {
            deps: ['vue']
        },
        'vueEventCalendar': {
            deps: ['vue']
        },
        'bmap': {
            deps: ['jquery'],
            exports: 'BMap'
        }
    }
})

require(['vue', 'iview', 'axios', 'jquery', 'async!bmap', 'heatmap'], function (Vue, iview, axios) {
    Vue.use(iview);
    new Vue({
        el: "#hot_maps",
        data() {
            return {
                map: {},
                points: [],
                newInfo: {
                    factoryname: "",
                    longitude: 116.82,
                    latitude: 40.01
                },
                type: [0], //默认选择为热力图
                types: [{
                        name: '热力图',
                        value: 0
                    },
                    {
                        name: '聚类分析',
                        value: 1
                    }
                ], //当前选择要加载的图层类型
                dateArr: [], //时间数据，生成dom用
                dataType: 0, //选择的数据类型
                dataTypes: [{
                        name: '运单量',
                        value: 0
                    },
                    {
                        name: '车次',
                        value: 1
                    }
                ], //装载量啥的，更改热力图匹配的数据
                stopMap: '暂停',
                btnDis: false,
                m: true,
                flag: false,
                display: true,
                clustering: false,
                hotDis: true,
                selectDis: true,
                CenterPointArr: [],
                cluNum: 4,
                cluNums: [{
                    value: 1
                }, {
                    value: 2
                }, {
                    value: 3
                }, {
                    value: 4
                }, {
                    value: 5
                }],
                dataArray: [], //返回数据
                month_Arr: [], //月份数据
                yearList: [], //年份数据
                year: [{
                        value: 2016
                    },
                    {
                        value: 2017
                    }
                ],
                monthList: 0, //选择的多少个月为间隔划分
                month: [{
                        value: 3
                    },
                    {
                        value: 6
                    },
                    {
                        value: 12
                    }
                ], //月份划分的区间
                months: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], //每个月的天数，忽略了闰年
                initsetInterval: 0, //清除定时器用
            }
        },
        mounted() {
            this.initMap();
        },
        watch: {
            type: 'checkType',
            yearList: 'checkData',
            dateArr: function () {
                if (this.dateArr.length > 1) {
                    this.btnDis = true;
                    this.stopMap = '暂停';
                    this.m = true;
                    return;
                }
                this.btnDis = false;
            }
        },
        methods: {
            initMap: function () {
                this.points.push(new BMap.Point(this.newInfo.longitude, this.newInfo.latitude));
                this.setMap();
            },
            setMap() {
                var map = new BMap.Map("hotmaps");
                // var centerAndZomm = map.getViewport(this.points);
                map.centerAndZoom(new BMap.Point(116.654788,39.919362), 11);
                map.enableScrollWheelZoom();
                this.map = map;
            },
            checkType() {
                /*
                 * 判断热力图、聚类
                 */
                if (this.type.length ==0) {
                   this.selectDis = false;
                } else {
                   this.selectDis = true;
                  
                  if(this.type[0] == 0){
                      this.display = true;
                      this.hotDis = true;
                      this.clustering = false;
                      this.cleanMap();
                  }
                  else if (this.type.length == 2) {
                      this.display = true;
                      this.hotDis = true;
                      this.clustering = false;
                      this.cleanMap();
                  } else {
                      this.display = false;
                      this.hotDis = false;
                      this.clustering = true;
                      this.cleanMap();
                  }
                }
            },
            checkData() {
                /*
                 * 判断年月是否选择
                 */
                if (this.yearList.length == 0 || this.monthList == '') {
                    return;
                } else {
                    window.clearInterval(this.activeMap);
                    let dom = document.getElementById('month-line');
                    this.map.clearOverlays();
                    dom.innerHTML = '';
                    this.handleMonth();
                }
            },
            customData(data) {
                /*
                 *用户选择时间区间
                 */
                if (this.monthList != 0) {
                    window.clearInterval(this.activeMap);
                    this.map.clearOverlays();
                    this.monthList = 0;
                    this.yearList = [];
                    this.dateArr = [];
                }
                if(this.type.length == 2 || this.type[0] == 0){
                    window.clearInterval(this.activeMap);
                    this.map.clearOverlays();
                    this.dataArray = [];
                    this.dateArr.push(data);
                }else{
                    this.dateArr=[];
                    this.dateArr.push(data);
                }
                this.clustering ? this.getOnlyClusterData() : this.getData();
            },
            getOnlyClusterData() {
                /*
                 * 获取聚类后台数据
                 */
                var _this=this;
                $.ajax({
                    url: "/YF/public/index.php/index/Service/getOnlyClusterData",
                    type: 'post',
                    dataType: 'json',
                    async: false,
                    data: {
                        start_time: _this.dateArr[0][0],
                        end_time: _this.dateArr[0][1],
                        center_count:_this.cluNum,
                    },
                    success: function (res) {
                        var res = JSON.parse(res)
                        if (res.code === 0) {
                            var data =res.data;
                            _this.cleanMap(); 
                            _this.setClusterPoint(data[1]);
                            _this.setCenterPointArray(data[0]);

                        } else {
                            _this.setMap();
                        }
                    },
                    error: function (data) {
                        console.log(data)
                    }
                })

            },
            handleMonth() {
                /*
                 *处理月份区间，获取时间数组
                 */
                let startStr = '';
                let endStr = '';
                this.dateArr = [];
                for (let i = 1; i <= this.yearList.length; i++) {
                    for (let j = 1; j <= 12; j += this.monthList) {
                        startStr = this.yearList[i - 1] + '-' + j + '-' + '01';
                        var temp = j + this.monthList - 2;
                        endStr = this.yearList[i - 1] + '-' + (j + this.monthList - 1) + '-' + this.months[temp];
                        let arr = [];
                        arr[0] = startStr;
                        arr[1] = endStr;
                        this.dateArr.push(arr);
                    }
                }
                this.getData();
            },
            getData() {
                /*
                 * 获取后台数据
                 */
                this.map.centerAndZoom(new BMap.Point(117.07, 39.98), this.map.getZoom());
                let ln = this.dateArr.length;
                var _this = this;
                var url;
                if(_this.dataType==0){
                    url="/YF/public/api/getHotMaps";
                }
                else if(_this.dataType==1){
                    url="/YF/public/index.php/index/Service/getCarCountHotMaps";
                }  
                for (let i = 0; i < ln; i++) {
                    $.ajax({
                        url: url,
                        type: 'post',
                        dataType: 'json',
                        async: false,
                        data: {
                            start_time: _this.dateArr[i][0],
                            end_time: _this.dateArr[i][1],
                        },
                        success: function (res) {
                            var res = JSON.parse(res)
                            if (res.code === 0) {

                                _this.dataArray.push(res.data);
                            } else {
                                _this.setMap();
                            }
                        },
                        error: function (data) {
                            console.log(data)
                        }
                    })
                }
                if (_this.type.length == 2) {
                    _this.getClustersPy();
                }
                _this.createDom();
            },
            cleanMap() {
                /*
                 *清除图层
                 *dom 时间轴节点
                 */
                this.dataArray = [];
                this.dateArr = [];
                var dom = document.getElementById('month-line');
                dom.innerHTML = '';
                this.yearList = [];
                this.monthList = '';
                window.clearInterval(this.activeMap);
                this.map.clearOverlays();
                this.flag = false;
                this.month_Arr = [];
            },
            /**
             * 在地图上加载每个聚类
             */
            setClusterPoint(data){
                console.log(data);
                for(var i=0;i<data.length;i++){
                    console.log(i)
                    for(var j=0;j<data[i].length;j++){
                        var poi = new BMap.Point(data[i][j][0], data[i][j][1]);
                        var myIcon = new BMap.Icon("../static/img/cluster"+i+".png", new BMap.Size(150, 200), {
                            anchor: new BMap.Size(12, 14), //中心点设置
                        });
                        var marker = new BMap.Marker(poi, {
                            icon: myIcon
                        });
                        this.map.addOverlay(marker);
                    }
                }
            }
            ,
            /**
             * 在地图上加载聚类中心点
             * @param {lng,lat} data 
             */
            setCenterPointArray(data) {
                data.forEach((item, index) => {
                    var CenterPoint = new BMap.Point(item.lng, item.lat);
                    var myIcon = new BMap.Icon("../static/img/location2.png", new BMap.Size(150, 200), {
                        anchor: new BMap.Size(12, 14), //中心点设置
                    });
                    //覆盖物
                    var marker = new BMap.Marker(CenterPoint, {
                        icon: myIcon
                    });
                    this.map.addOverlay(marker);
                })
            },
            /**
             * 聚类中心点数据：this.CenterPointArr
             */
            getClustersPy() {
                var _this = this;
                for (var i = 0; i < _this.dateArr.length; i++) {
                    $.ajax({
                        url: "/YF/public/index.php/index/Service/getClustersPy",
                        type: 'post',
                        dataType: 'json',
                        async: false,
                        data: {
                            start_time: _this.dateArr[i][0],
                            end_time: _this.dateArr[i][1],
                            center_count:_this.cluNum,
                        },
                        success: function (res) {
                            var res = JSON.parse(res)
                            if (res.code === 0) {
                                _this.CenterPointArr.push(res.data);
                            } else {
                                _this.setMap();
                            }
                        },
                        error: function (data) {
                            console.log(data)
                        }
                    })

                }

            },
            /**
             * 热力图
             * @param {*} data={lng,lat,count} 
             */
            hot_map(data) {
                this.flag = true;
                var points = data;
                var status = this.isSupportCanvas();
                if (!status) {
                    alert('热力图目前只支持有canvas支持的浏览器,您所使用的浏览器不能使用热力图功能~')
                }
                //详细的参数,可以查看heatmap.js的文档 https://github.com/pa7/heatmap.js/blob/master/README.md  
                //参数说明如下:  
                /* visible 热力图是否显示,默认为true  
                 * opacity 热力的透明度,1-100  
                 * radius 势力图的每个点的半径大小  
                 * gradient  {JSON} 热力图的渐变区间 . gradient如下所示  
                 *  {  
                        .2:'rgb(0, 255, 255)',  
                        .5:'rgb(0, 110, 255)',  
                        .8:'rgb(100, 0, 255)'  
                    }  
                    其中 key 表示插值的位置, 0~1.  
                        value 为颜色值.  
                 */
                heatmapOverlay = new BMapLib.HeatmapOverlay({
                    "radius": 20
                });
                this.map.addOverlay(heatmapOverlay);

                heatmapOverlay.setDataSet({
                    data: points,
                    max: 100,
                    heatmapOverlay: heatmapOverlay
                });
                this.SetInfoWindow(data);
            },
            /**
             * 设置信息窗口
             * @param {*} data={lng,lat,count} 
             */
            SetInfoWindow(data) {
                data.forEach((item, index) => {
                    var hotPoint = new BMap.Point(item.lng, item.lat);
                    //覆盖物
                    var myIcon = new BMap.Icon("../static/img/transparent.png", new BMap.Size(20, 20), {
                        anchor: new BMap.Size(12, 14), //中心点设置
                    });
                    var marker = new BMap.Marker(hotPoint, {
                        icon: myIcon
                    });
                    this.map.addOverlay(marker);
                    var content = item.count.toString();
                    var opts = {
                        width: 20, // 信息窗口宽度
                        height: 10, // 信息窗口高度
                        title: "合计单数", // 信息窗口标题
                        enableMessage: true //设置允许信息窗发送短息
                    };
                    marker.addEventListener("click", function (e) {
                        var p = e.target;
                        var point = new BMap.Point(p.getPosition().lng, p.getPosition().lat);
                        var infoWindow = new BMap.InfoWindow(content, opts); // 创建信息窗口对象 
                        this.map.openInfoWindow(infoWindow, point);
                    })
                });
            },
            isSupportCanvas() {
                var elem = document.createElement('canvas');
                return !!(elem.getContext && elem.getContext('2d'));
            },
            stopMaps() {
                if (this.m) {
                    this.stopMap = '开始';
                    this.stopActive();
                    this.m = false;
                } else {
                    this.stopMap = '暂停';
                    this.activePoint();
                    this.m = true;
                }
            },
            activePoint() {
                let dom = document.getElementsByClassName('ivu-timeline-item-head');
                let p = document.getElementsByClassName('timeline-p');
                let len = dom.length;
                let i = 0;
                var that = this;
                for (let j = 0; j < len; j++) {
                    dom[j].style.background = 'blue';
                    p[j].style.background = '#1290eac4';
                }
                // console.log(this.dataArray);
                that.activeMap = window.setInterval(function () {
                    if (i == len) {
                        i = 0;
                    }
                    if (i == 0) {
                        dom[i].style.background = 'red';
                        p[i].style.background = '#ea1212b8';
                        dom[len - 1].style.background = 'blue';
                        p[len - 1].style.background = '#1290eac4';
                    } else {
                        dom[i].style.background = 'red';
                        p[i].style.background = '#ea1212b8';
                        dom[i - 1].style.background = 'blue';
                        p[i - 1].style.background = '#1290eac4';
                    }
                    that.map.clearOverlays();
                    that.hot_map(that.dataArray[i]);
                    if (that.type.length == 2) {
                        that.setCenterPointArray(that.CenterPointArr[i]);
                    }
                    i++;
                }, 2000);
            },
            stopActive() {
                window.clearInterval(this.activeMap);
            },
            createDom() {
                let dom = document.getElementById('month-line');
                if (document.getElementsByClassName('ivu-timeline-item')) {
                    window.clearInterval(this.initsetInterval);
                    this.map.clearOverlays();
                    dom.innerHTML = '';
                }
                let _this = this;
                for (let i = 0; i < this.dateArr.length; i++) {
                    (function () {
                        var li = document.createElement('li');
                        li.classList.add('ivu-timeline-item');
                        var div1 = document.createElement('div');
                        var div2 = document.createElement('div');
                        var div3 = document.createElement('div');
                        var p = document.createElement('p');
                        div1.classList.add('ivu-timeline-item-tail');
                        div2.classList.add('ivu-timeline-item-head');
                        div2.classList.add('ivu-timeline-item-head-blue');
                        div3.classList.add('ivu-timeline-item-content');
                        p.classList.add('timeline-p');
                        p.innerText = _this.dateArr[i][0] + '至' + _this.dateArr[i][1];
                        div3.appendChild(p);
                        li.appendChild(div1);
                        li.appendChild(div2);
                        li.appendChild(div3);
                        dom.appendChild(li);
                    }(i))
                }
                this.flag = true;
                this.activePoint();
            }
        },
        created() {},
        computed: {}
    });
});
